package com.rao.travel.service.impl;

import com.rao.travel.dao.UserDao;
import com.rao.travel.pojo.Role;
import com.rao.travel.pojo.UserInfo;
import com.rao.travel.service.UserService;
import com.rao.travel.utils.PasswordEncoderUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author Srao
 * @version 1.0
 * @className UserServiceImpl
 * @date 2019/10/30 22:25
 * @package com.rao.travel.service.impl
 * @description
 */
@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserInfo userInfo = null;
        try {
            userInfo = userDao.findByUsername(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //User user = new User(userInfo.getUsername(), "{noop}"+userInfo.getPassword(), getAuthority(userInfo.getRoles()));
        User user = new User(userInfo.getUsername(), userInfo.getPassword(), userInfo.getStatus() == 1, true, true, true, getAuthority(userInfo.getRoles()));
        return user;
    }

    public List<SimpleGrantedAuthority> getAuthority(List<Role> roles) {
        List<SimpleGrantedAuthority> list = new ArrayList<>();
        for(Role role : roles){
            list.add(new SimpleGrantedAuthority(role.getRoleName()));
        }
        return list;
    }

    /*查询所有用户*/
    @Override
    public List<UserInfo> findAll() {
        return userDao.findAll();
    }

    /*保存一个用户*/
    @Override
    public void save(UserInfo userInfo) {
        String encoder = PasswordEncoderUtils.encoder(userInfo.getPassword());
        userInfo.setPassword(encoder);
        userDao.save(userInfo);
    }

    /*根据用户id查询用户*/
    @Override
    public UserInfo findById(String id) {
        return userDao.findById(id);
    }

    /*查询该用户没有的角色*/
    @Override
    public List<Role> findOtherRole(UserInfo userInfo) {
        return userDao.findOtherRole(userInfo);
    }

    /*为用户添加角色*/
    @Override
    public void addRoleToUser(String userId, String[] ids) {
        for (String roleId : ids){
            userDao.addRoleToUser(userId, roleId);
        }
    }
}
